package com.sheepone.util.beanconvert;

import com.sheepone.util.ObjectUtil;
import com.sheepone.util.ReflectUtil;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Miss.杨
 * @description
 * @since 2024/3/11 - 16:51
 */
public class MapBeanConvertUtil {

    public static  Map<String, Object> simpleStringMap(Object object) {
        Class<?> clazz = object.getClass();
        Field[] fields = ReflectUtil.accessibleDeclaredFields(clazz);
        HashMap<String, Object> map = new HashMap<>();
        try {
            for (Field field : fields) {
                map.put(field.getName(), field.get(object).toString());
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return map;
   }

    public static  Map<String, Object> handleObjectOnlyContainBasicTypeToObjectMap(Object object) {
        Class<?> clazz = object.getClass();
        if (!ObjectUtil.isOnlyContainBasicType(clazz)) {
            throw  new RuntimeException("传入的参数类型不正确");
        }
        Field[] fields = ReflectUtil.accessibleDeclaredFields(clazz);
        HashMap<String, Object> map = new HashMap<>();
        try {
            for (Field field : fields) {
                map.put(field.getName(), field.get(object));
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return map;
    }

    public static  Map<String, String> handleObjectOnlyContainBasicTypeToStringMap(Object object) {
        Class<?> clazz = object.getClass();
        if (!ObjectUtil.isOnlyContainBasicType(clazz)) {
            throw  new RuntimeException("传入的参数类型不正确");
        }
        Field[] fields = ReflectUtil.accessibleDeclaredFields(clazz);
        HashMap<String, String> map = new HashMap<>();
        try {
            for (Field field : fields) {
                map.put(field.getName(), field.get(object).toString());
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return map;
    }
}
